#!/usr/bin/python

import tsw.cliservice as cli    
import sys
import tsw.service as service
import tsw.config as config
import tsw.confighandler as confighandler

helpInfo = """
    tinyswitch is the cli of tinyswitch. 
    Usage tswitch [Option]
    

    OPTION 

        -v version
        -r reconfig tinyswitch
        -d delete a proxy entry from tinyswitch
        -a add a new proxy entry 
        -l list all proxy entries managed by tinyswitch
        -s [name] set/(switch to) another proxy as system proxy server (root permission needed). if [name] is given, tinyproxy will set the [name] proxy as system proxy, otherwise proxy will be set interactively.
        -h print help message
            """


def usage():
    """print usage information"""
    print helpInfo

def version():
    """print version"""
    print config.VERSION

operations = {
    '-a'  : cli.add,
    '-r'  : cli.reconfig,
    '-d'  : cli.remove,
    '-l'  : cli.all,
    '-s'  : cli.set,
    '-sn' : cli.setByName,
    '-h'  : usage,
    '-v'  : version
    }

if __name__ == '__main__':
    #check if config file init is required
    if confighandler.requireInit():
        confighandler.initHomeConfPath() 
        #go to reconfig
        cli.reconfig()

    #load config
    if not confighandler.loadConfig():
        print 'Error: config file cannot be found, run "tinyswitch -r" to fix it'
        exit(1)
    
    resyncOK = service.resync_proxy()
    if not resyncOK:
        print "Error: your tinyproxy config file has error, please fix that first."
        exit(1)
    
    if sys.argv.__len__() <2 or not sys.argv[1]:
        usage()
        sys.exit(1)
    else: 
        if sys.argv[1] == '-s' and sys.argv.__len__() == 3 and  sys.argv[2]: # -s with name
            f = operations.get('-sn')
            f(sys.argv[2]) 
            sys.exit(0)
        else:
            f = operations.get(sys.argv[1])
            f() if f else usage()
            sys.exit(0)

